package com.bayihouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.constant.CommonConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.mapper.AdministerMapper;
import com.bayihouse.model.entity.Administer;
import com.bayihouse.model.entity.FileInfo;
import com.bayihouse.model.enums.AdministerRoleEnum;
import com.bayihouse.model.request.administer.AdministerQueryRequest;
import com.bayihouse.model.request.administer.AdministerRegisterRequest;
import com.bayihouse.model.vo.AdministerVO;
import com.bayihouse.model.vo.LoginAdministerVO;
import com.bayihouse.service.AdministerService;
import com.bayihouse.service.FileInfoService;
import com.bayihouse.utils.MinioUtils;
import com.bayihouse.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【administer(用户)】的数据库操作Service实现
 * @createDate 2024-09-17 10:28:03
 */
@Service
@Slf4j
public class AdministerServiceImpl extends ServiceImpl<AdministerMapper, Administer>
        implements AdministerService {

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "luojialong";


    @Resource
    private AdministerMapper administerMapper;


    @Resource
    private MinioUtils minioService;

    @Lazy
    @Resource
    private FileInfoService fileInfoService;


    @Override
    public LoginAdministerVO administerLogin(String administerAccount, String administerPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(administerAccount, administerPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (administerAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (administerPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + administerPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<Administer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", administerAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        Administer administer = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (administer == null) {
            log.info("Administer login failed, administerAccount cannot match administerPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        if (administer.getUserRole() < 0) {
            log.info("Administer login failed, administerAccount is banned");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已被封禁");
        }
        // 3. 记录用户的登录态
        System.out.println("登录成功");
        System.out.println("-------------------------------------");
        System.out.println("登录用户的信息service");
        System.out.println(administer);
        System.out.println("-------------------------------------");
        request.getSession().setAttribute(AdministerConstant.Administer_LOGIN_STATE, administer);
        return this.getLoginAdministerVO(administer);
    }

    @Override
    public Long getByUserName(String addUserName, String addUserTelephone) {
        QueryWrapper<Administer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", addUserName);
        queryWrapper.eq("telephone", addUserTelephone);
        Administer administer = this.baseMapper.selectOne(queryWrapper);
        return administer.getId();
    }


    /**
     * 获取当前登录用户
     *
     * @param
     * @return
     */
    @Override
    public Administer getLoginAdminister(HttpServletRequest request) {
        // 先判断是否已登录
        Object AdministerObj = request.getSession().getAttribute(AdministerConstant.Administer_LOGIN_STATE);
        Administer currentAdminister = (Administer) AdministerObj;
        if (currentAdminister == null || currentAdminister.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        long AdministerId = currentAdminister.getId();
        currentAdminister = this.getById(AdministerId);
        if (currentAdminister == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentAdminister;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public Administer getLoginAdministerPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object AdministerObj = request.getSession().getAttribute(AdministerConstant.Administer_LOGIN_STATE);
        Administer currentAdminister = (Administer) AdministerObj;
        if (currentAdminister == null || currentAdminister.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long AdministerId = currentAdminister.getId();
        return this.getById(AdministerId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object AdministerObj = request.getSession().getAttribute(AdministerConstant.Administer_LOGIN_STATE);
        Administer Administer = (Administer) AdministerObj;
        return isAdmin(Administer);
    }

    @Override
    public boolean isAdmin(Administer administer) {
        return administer.getUserRole() > AdministerConstant.DEFAULT_ROLE;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean administerLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(AdministerConstant.Administer_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(AdministerConstant.Administer_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginAdministerVO getLoginAdministerVO(Administer administer) {
        if (administer == null) {
            return null;
        }
        LoginAdministerVO loginAdministerVO = new LoginAdministerVO();
        BeanUtils.copyProperties(administer, loginAdministerVO);
        try {
            FileInfo fileInfo = fileInfoService.getById(administer.getUserAvatar());
            String url = minioService.getUrl(fileInfo.getFileName());
            loginAdministerVO.setUserAvatarUrl(url);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            loginAdministerVO.setUserAvatarUrl(null);
        }
        return loginAdministerVO;
    }

    @Override
    public AdministerVO getAdministerVO(Administer administer) {
        if (administer == null) {
            return null;
        }
        AdministerVO administerVO = AdministerVO.objToVo(administer);
        try {
            FileInfo fileInfo = fileInfoService.getById(administer.getUserAvatar());
            String url = minioService.getUrl(fileInfo.getFileName());
            administerVO.setUserAvatarUrl(url);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            administerVO.setUserAvatarUrl(null);
        }
        return administerVO;
    }

    @Override
    public List<AdministerVO> getAdministerVOList(List<Administer> AdministerList) {
        if (CollectionUtils.isEmpty(AdministerList)) {
            return new ArrayList<>();
        }
        return AdministerList.stream().map(this::getAdministerVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<Administer> getQueryWrapper(AdministerQueryRequest administerQueryRequest) {
        if (administerQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = administerQueryRequest.getId();
        String userName = administerQueryRequest.getUserName();
        Integer userRole = administerQueryRequest.getUserRole();
        String telephone = administerQueryRequest.getTelephone();
        String sortField = administerQueryRequest.getSortField();
        String sortOrder = administerQueryRequest.getSortOrder();

        QueryWrapper<Administer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(userRole != null, "userRole", userRole);
        queryWrapper.like(StringUtils.isNotBlank(telephone), "telephone", telephone);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_DESC),
                sortField);
        return queryWrapper;
    }

    @Override
    public long administerRegister(AdministerRegisterRequest administerRegisterRequest) {
        Administer administer = new Administer();
        BeanUtils.copyProperties(administerRegisterRequest, administer);
        String administerAccount = administer.getUserAccount();
        String administerPassword = administer.getUserPassword();
        String checkPassword = administerRegisterRequest.getUserCheckPassword();
        System.out.println(administerAccount + "+ " + administerPassword + "+ " + checkPassword);
        // 1. 校验
        if (StringUtils.isAnyBlank(administerAccount, administerPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (administerAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (administerPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!administerPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (administerAccount.intern()) {
            // 账户不能重复
            QueryWrapper<Administer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", administerAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + administerPassword).getBytes());
            // 3. 插入数据
            administer.setUserPassword(encryptPassword);
            boolean saveResult = this.save(administer);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return administer.getId();
        }
    }


}




